const { ethers } = require("hardhat");

async function main() {
    console.log("🐛 Ganache 连接调试...\n");

    try {
        // 1. 检查网络配置
        const config = require('../hardhat.config.js');
        console.log("📋 Hardhat 配置中的网络:");
        Object.keys(config.networks).forEach(network => {
            if (config.networks[network].url) {
                console.log(`  - ${network}: ${config.networks[network].url}`);
            } else {
                console.log(`  - ${network}: (无URL配置)`);
            }
        });

        // 2. 尝试连接到 Ganache
        console.log("\n🔗 尝试连接到 Ganache...");
        const provider = ethers.provider;

        // 获取网络信息
        const network = await provider.getNetwork();
        console.log(`✅ 连接成功!`);
        console.log(`   链ID: ${network.chainId}`);
        console.log(`   网络名称: ${network.name}`);

        // 获取区块号
        const blockNumber = await provider.getBlockNumber();
        console.log(`   当前区块: ${blockNumber}`);

        // 正确的方式获取账户 - 使用 getSigners()
        const signers = await ethers.getSigners();
        console.log(`   可用账户数: ${signers.length}`);

        if (signers.length > 0) {
            for (let i = 0; i < Math.min(signers.length, 3); i++) {
                const signer = signers[i];
                const balance = await provider.getBalance(signer.address);
                console.log(`   账户 ${i}: ${signer.address}`);
                console.log(`       余额: ${ethers.formatEther(balance)} ETH`);
            }

            if (signers.length > 3) {
                console.log(`   ... 还有 ${signers.length - 3} 个账户`);
            }
        }

        console.log("\n🎉 Ganache 连接正常，可以开始部署!");

    } catch (error) {
        console.log("❌ 连接失败:", error.message);

        // 提供具体的故障排除建议
        console.log("\n🔧 故障排除:");
        console.log("1. 确保 Ganache Docker 容器正在运行");
        console.log("2. 检查 Ganache 端口是否确实是 8545");
        console.log("3. 尝试重启 Ganache 容器");
        console.log("4. 检查防火墙设置");
    }
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("调试失败:", error);
        process.exit(1);
    });